/*
 * @lc app=leetcode.cn id=110 lang=javascript
 *
 * [110] 平衡二叉树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {boolean}
 */
var isBalanced = function(root) {
    let getDeep = (root) => {
        if (!root) {
            return 0
        }
        let Ldeep = getDeep(root.left) + 1
        let Rdeep = getDeep(root.right) + 1
        return Math.max(Ldeep, Rdeep)
    }
    let compareTree = (root) => {
        if (!root) {
            return true
        }
        if (root.left && root.right) {
            if (-1 <= getDeep(root.left) - getDeep(root.right) &&  getDeep(root.left) - getDeep(root.right) <= 1) {
                return compareTree(root.left) && compareTree(root.right)
            }
            return false
        } else {
            if(getDeep(root.left) <= 1 && getDeep(root.right) <= 1) {
                return true
            }
            return false
        }
    }
    return compareTree(root)
};
// @lc code=end

/* 
    这种方法是自顶向下的递归
    自底向上的递归，可以降低时间复杂度
*/

